package zero.tech.games.common;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import zero.tech.games.common.topic.ClubMemberChange;
import zero.tech.games.entity.games.ClubMember;
import zero.tech.redis.cache.RedisUtil;
import zero.tech.redis.topic.TopicChannelType;
import zero.tech.redis.topic.service.api.IRedisMsgService;

@Component
public class ClubMemberUtil {
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private IRedisMsgService redisMsgService;
	public ClubMember getClubMember(int club_id,int uid) {
		String str=(String)redisUtil.hget(RedisConsts.A_CLUBMEMBER+"_"+club_id,String.valueOf(uid));
		ClubMember clubMember=JSONObject.parseObject(str, ClubMember.class);
		return clubMember;
	}
	
	public Map<Integer,ClubMember> getClubMemberBatch(int club_id,int...uids) {
		Map<Integer,ClubMember> map=new HashMap<Integer, ClubMember>();
		if(uids.length>0) {
			String[] keys=new String[uids.length];
			for(int i=0;i<uids.length;i++) {
				keys[i]=String.valueOf(uids[i]);
			}
			Map<String, String> result=redisUtil.hmget(RedisConsts.A_CLUBMEMBER+"_"+club_id,keys);
			for(Entry<String,String> entry:result.entrySet()) {
				String key=entry.getKey();
				String val=entry.getValue();
				if(val!=null) {
					ClubMember clubMember=JSONObject.parseObject(val, ClubMember.class);
					map.put(Integer.valueOf(key), clubMember);
				}else {
					map.put(Integer.valueOf(key), null);
				}
			}
		}
		return map;
	}
	
	public void setClubMember(ClubMember clubMember) {
		int club_id=clubMember.getClub_id();
		int uid=clubMember.getUid();
		redisUtil.hset(RedisConsts.A_CLUBMEMBER+"_"+club_id,String.valueOf(uid),JSONObject.toJSONString(clubMember));
	}

	public void setClubMemberBatch(int club_id,List<ClubMember> clubMembers) {
		Map<Object,Object> map=new HashMap<>();
		for(ClubMember clubMember:clubMembers) {
			int uid=clubMember.getUid();
			map.put(String.valueOf(uid), JSONObject.toJSONString(clubMember));
		}
		redisUtil.hmset(RedisConsts.A_CLUBMEMBER+"_"+club_id, map);
	}

	public void notifyClubMemberChange(int club_id,int...uids) {
		ClubMemberChange clubMemberChange=new ClubMemberChange();
		clubMemberChange.setClub_id(club_id);
		for(int uid:uids) {
			clubMemberChange.getUids().add(uid);
		}
		redisMsgService.pulishRedisTopic(TopicChannelType.CLUB_MEMBER_CHANGE, TopicOrder.ACCOUNT_CHANGE, clubMemberChange);
	}
}
